#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->lineEdit->setPlaceholderText("input item text");
    ui->lineEdit->setAlignment(Qt::AlignCenter);

    ui->pushButton_addItemTop->setText("add top item");
    ui->pushButton_removeItem->setText("remove item chosen");
    ui->pushButton_addItemChild->setText("add item child");

    ui->treeWidget->setHeaderLabel("animals");
    QTreeWidgetItem* topItem1 = new QTreeWidgetItem();
    QTreeWidgetItem* topItem2 = new QTreeWidgetItem();
    QTreeWidgetItem* topItem3 = new QTreeWidgetItem();
    topItem1->setText(0,"tiger");
    topItem2->setText(0,"cat");
    topItem3->setText(0,"bird");
    ui->treeWidget->addTopLevelItem(topItem1);
    ui->treeWidget->addTopLevelItem(topItem2);
    ui->treeWidget->addTopLevelItem(topItem3);
    QTreeWidgetItem* topChildItem1 = new QTreeWidgetItem();
    QTreeWidgetItem* topChildItem2 = new QTreeWidgetItem();
    QTreeWidgetItem* topChildItem3 = new QTreeWidgetItem();
    topChildItem1->setText(0,"tiger1");
    topChildItem2->setText(0,"tiger2");
    topChildItem3->setText(0,"tiger3");
//    topItem1->addChild(topChildItem1);
//    topItem1->addChild(topChildItem2);
//    topItem1->addChild(topChildItem3);
    QList<QTreeWidgetItem*>arr;
    arr.push_back(topChildItem1);
    arr.push_back(topChildItem2);
    arr.push_back(topChildItem3);
    topItem1->addChildren(arr);

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_addItemTop_clicked()
{
    const QString itemText(ui->lineEdit->text());
    ui->lineEdit->clear();
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0,itemText);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_addItemChild_clicked()
{
    QTreeWidgetItem* itemPos = ui->treeWidget->currentItem();
    if(!itemPos)
        return;
    const QString itemText(ui->lineEdit->text());
    ui->lineEdit->clear();
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0,itemText);
    itemPos->addChild(item);
}

void Widget::on_pushButton_removeItem_clicked()
{
    QTreeWidgetItem* itemPos = ui->treeWidget->currentItem();
    if(!itemPos)
        return;
    if(!itemPos->parent())
    {
        int index = ui->treeWidget->indexOfTopLevelItem(itemPos);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
        itemPos->parent()->removeChild(itemPos);

}
